package com.tiennt.android.smartcaller.utils;

import java.io.InputStream;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;

public class ContactUtils {

	public static Bitmap getContactPhoto(ContentResolver contentResolver,
			String contactId) {
		Uri contactUri = Uri.withAppendedPath(
				ContactsContract.Contacts.CONTENT_URI, contactId);
		SmartCallerUtils.log(contactUri + "");

		InputStream photoStream = ContactsContract.Contacts
				.openContactPhotoInputStream(contentResolver, contactUri);
		if (photoStream == null) {
			return null;
		}
		return BitmapFactory.decodeStream(photoStream);
	}

	public static Bitmap loadContactPhoto(ContentResolver cr, String contactId,
			String photo_id) {

		Uri uri = ContentUris.withAppendedId(
				ContactsContract.Contacts.CONTENT_URI,
				Long.parseLong(contactId));
		InputStream input = ContactsContract.Contacts
				.openContactPhotoInputStream(cr, uri);
		if (input != null) {
			return BitmapFactory.decodeStream(input);
		} else {
			SmartCallerUtils.log("First try failed");
		}

		byte[] photoBytes = null;

		if (photo_id != null) {

			Uri photoUri = ContentUris
					.withAppendedId(ContactsContract.Data.CONTENT_URI,
							Long.parseLong(photo_id));

			Cursor c = cr
					.query(photoUri,
							new String[] { ContactsContract.CommonDataKinds.Photo.PHOTO },
							null, null, null);

			try {
				if (c.moveToFirst())
					photoBytes = c.getBlob(0);

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();

			} finally {
				c.close();
			}

			if (photoBytes != null)
				return BitmapFactory.decodeByteArray(photoBytes, 0,
						photoBytes.length);

		}
		return null;

	}
}
